package com.sz.biz.trade.goods.service.impl;

import com.sz.biz.trade.goods.entity.GoodsType;
import com.sz.biz.common.AbstractVersionEntityService;
import com.sz.biz.trade.goods.service.GoodsTypeService;
import com.sz.biz.trade.goods.dto.GoodsTypeDto;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.TreeNode;
import com.sz.common.base.utils.EntityUtils;
import com.sz.common.base.utils.TreeBuilder;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Function: 商品类型<br>
 * Author: penghui.zheng <br>
 * Date: 2017-07-13 09:30:00
 */
@Service("goodsTypeService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class GoodsTypeServiceImpl extends AbstractVersionEntityService implements GoodsTypeService {

	@Override
	protected String getMapperNamespace() {
		return "GoodsTypeMapper";
	}

	@Override
	public List<TreeNode> getGoodsType() {
		List<TreeNode> nodes = new ArrayList<>();
		ParamData pd = new ParamData();
		List<GoodsTypeDto> list = dao.findForList("GoodsTypeMapper.findGoodsType", pd, GoodsTypeDto.class);
		setListData(list, nodes);
		Map<String, GoodsTypeDto> typeMap = EntityUtils.getStringKeyMapFromBeans(list, "id");
         for (TreeNode node : nodes) {

             // 设置父节点
             GoodsTypeDto goodsType = typeMap.get(node.getParentId() + "");
             while (goodsType != null) {
                 node.getParentIds().add(0, goodsType.getId());
                 goodsType = typeMap.get(goodsType.getParentId() + "");
             }
         }

         return TreeBuilder.buildListToTree(nodes);
	}

    @Override
    public GoodsType findById(Integer id) {
        return (GoodsType) dao.findForObject(getSqlName("selectByPrimaryKey"), id);
    }

    /**
     * 设置用户数
     *
     * @param list       list
     * @param nodes      nodes
     */
    private void setListData(List<GoodsTypeDto> list, List<TreeNode> nodes) {
        for (GoodsTypeDto goodsTypeDto : list) {
        	TreeNode treeNode = new TreeNode();
            treeNode.setId(goodsTypeDto.getId());
            treeNode.setName(goodsTypeDto.getName());
            treeNode.setParentId(goodsTypeDto.getParentId());
            treeNode.setLeaf(goodsTypeDto.getIsLeaf());
            nodes.add(treeNode);
        }
    }

}
